<template>
    <div class="address">
        <van-nav-bar
            title="管理收货地址"
            left-text=""
            :right-text="orderAddr"
            left-arrow
            @click-left="onClickLeft"
            @click-right="onClickRight"
        />
        <van-address-list
            v-model="chosenAddressId"
            :list="list"
            default-tag-text="默认"
            @add="onAdd"
            @edit="onEdit"
        ></van-address-list>
    </div>
</template>

<script setup>
import { useStore } from 'vuex';
import { computed, ref, reactive, toRef } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { requestGet } from '@/utils/Request.js';
const router = useRouter();
const route = useRoute();
const store = useStore();
const token = store.state.user.token;
let chosenAddressId = ref('');
let list = ref([]);
let orderAddr = ref('');
let chosenAddr = store.state.address.chosenAddrId;
const fromPath = route.query.redirct;
(async () => {
    const res = await requestGet('/address', token);
    store.commit('address/getAddress', res.data.result);
    let tempList = res.data.result;
    if (!chosenAddr) {
        for (let i = 0; i < tempList.length; i++) {
            if (tempList[i].default_set == '1') {
                chosenAddressId.value = tempList[i].id.toString();
                let defaultAddr = tempList.splice(i, 1);
                tempList.unshift(defaultAddr[0]);
                break;
            }
        }
    } else {
        orderAddr.value = '确定';
        chosenAddressId.value = chosenAddr.toString();
        let defaultAddr = tempList.splice(
            tempList.indexOf(ele => (ele.id = chosenAddr)),
            1
        );
        tempList.unshift(defaultAddr[0]);
    }

    tempList.forEach((ele, i) => {
        list.value[i] = {};
        list.value[i]['id'] = ele['id'].toString();
        list.value[i]['name'] = ele['name'];
        list.value[i]['tel'] = ele['phone'];
        list.value[i]['address'] = ele['area_name'] + ele['desc'] + ele['area'];
        list.value[i]['isDefault'] = +ele['default_set'];
    });
})();

const onClickLeft = () => {
    router.push(fromPath);
};
// 确认选择的地址继续提交订单
const onClickRight = () => {
    store.commit('address/changeChosenAddr', chosenAddressId.value);
    router.push(`/pay`);
};
const onAdd = () => {
    store.commit('address/changeChosenAddr', '');
    router.push(`/chanAddress?redirct=${fromPath}`);
};
const onEdit = () => {
    if (chosenAddressId.value) {
        store.commit('address/changeChosenAddr', chosenAddressId.value);
        router.push(`/chanAddress?redirct=${fromPath}`);
    }
};
</script>

<style lang="scss" scoped></style>
